const app = getApp()
const ctx = wx.createCanvasContext('canvas1')
//const ctx = wx.canv('canvas1')
const ww = app.globalData.ww
const hh = app.globalData.hh

Page({
  data: {
    ww: ww,
    hh: hh
  },

  onLoad() {
    var that = this;
    wx.startAccelerometer({
      success(res) {
        that.start()
      }

    });

    this.hf_w = ww / 2;
    this.hf_h = hh / 2;
    this.x = 0;
    this.y = 0;
    this.ax = 0;
    this.ay = 0;
    this.vx = 0;
    this.vy = 0;
    this.draw();

  },

  start() {
    var vt = 5, that = this;
    wx.onAccelerometerChange(function (res) {
      that.ax = res.x * vt;
      that.ay = res.y * vt;

    });

    setInterval(function () {
      var lo = ww / hh > 1;
      if (lo) {
        that.vx = that.vx + that.ay;
        that.vy = that.vy + that.ax;
      } else {
        that.vy = that.vy - that.ay;
        that.vx = that.vx + that.ax;
      }

      that.vx = that.vx * 0.98;
      that.vy = that.vy * 0.98;
      that.y = parseInt(that.y + that.vy / 50);
      that.x = parseInt(that.x + that.vx / 50);
      that.boundingBoxCheck();
      that.draw();

    }, 100 / 6)

  },


  end() {
    wx.stopAccelerometer()
  },


  draw() {
    console.log(this.x);
    ctx.clearRect(0, 0, ww, hh);
    ctx.fillRect(0, 0, ww, hh)
    ctx.fill()
    ctx.beginPath();
    ctx.arc(this.x, this.y, 20, 0, Math.PI * 2);
    ctx.setFillStyle('#FFFFFF');
    ctx.fill()
    ctx.draw();

  },

  boundingBoxCheck() {

    if (this.x < 0) { this.x = 0; this.vx = -this.vx; }
    if (this.y < 0) { this.y = 0; this.vy = -this.vy; }
    if (this.x > ww - 20) { this.x = ww - 20; this.vx = -this.vx; }
    if (this.y > hh - 20) { this.y = hh - 20; this.vy = -this.vy; }

  }

 

})


